<?php
namespace app\api\controller;

use think\Controller;
use think\Cache;
use think\Request;
use think\Db;
use think\Cookie;

class Search extends Controller
{
    protected $beforeActionList = [
        'isajax',
        'publog' => ['only'=>'publicationlist'],
        'artlog' => ['only'=>'getarticle'],
    ];

    protected function isajax()
    {
        if(!Request::instance()->isAjax()) {
            exit;
        }
    }

    protected function publog()
    {
        $sid = filter_keyword(input('post.pid'));
        if(!Cookie::has('pub'.$sid)){
            $ip = getIp(0);
            Db::connect('user_db')->execute('insert into s_visit_s (uid, sid, visitip, visittime) values (?, ?, ?, ?)',[0, $sid, $ip, time()]);
            Cookie::set('pub'.$sid, $sid,3600);
        }
    }

    protected function artlog()
    {
        $ip = getIp(0);
        $docid = input('post.docid');
        Db::connect('user_db')->execute('insert into s_down_a (uid, docid, visitip, downtime) values (?, ?, ?, ?)',[0, $docid, $ip, time()]);
    }

    //检索系统首页
    public function keyword()
    {
        $keyword = filter_keyword(input('post.keyword'));
        $res = Db::query('select * from s_keywords where keyname like ? limit 10',[$keyword.'%']);
        return $res;
    }

    //取数据总数
    public function getTotal()
    {
        $total = Cache::get('Total');
        if(empty($total)){
            $res = Db::query('select tname from s_class');
            $sql = '';
            foreach($res as $id=>$vo){
                $sql = $sql.' select count(*) as a from s_'.$vo['tname'].' union all';
            }
            $sql = 'select sum(a) as total from ('. substr($sql,0,-9)  .')t';
            $total = Db::query($sql);
            $total = $total[0]['total'];
            if(empty($total)){
                return 'null';
            }else{
                Cache::set('Total',$total,3600);
                return $total;
            }
        }
        else{
            return $total;
        }
    }

    //总检索
    public function search()
    {
        $keyword = input('post.keyword');
        $cid = intval (input('post.cid'));
        $year = intval (input('post.year'));
        $cpage = intval (input('post.page'));
        $pagesize = intval (input('post.limit'));
        import('Sphinx.SphinxClient', EXTEND_PATH, '.class.php');
        $search = new \SphinxClient();
        $search->SetServer(config('sphinxhost'),config('sphinxport'));	//服务器地址，端口
        $search->SetMatchMode(SPH_MATCH_EXTENDED2);	// 匹配模式
        $weights = array(
            'mtitle' => 9999,
            'sourcename' => 6666
        );
        $search->SetFieldWeights($weights);	//设置字段权重
        $search->SetSortMode(SPH_SORT_RELEVANCE);	//排序方式 匹配度
        $search->SetLimits(($cpage-1)*$pagesize, $pagesize); //分页设置
        debug('begin');
            if(!empty($cid)){ $search->SetFilter('cid', array($cid));}	//分库检索
            if(empty($year)){
                $search->AddQuery($keyword, config('myindex'));	//添加查询（全字段搜索）
                if($cpage==1){
                    $search->SetLimits(0,50);
                    $search->SetGroupBy('year', SPH_GROUPBY_ATTR);	//按年分组
                    $search->AddQuery($keyword, config('myindex'));
                }
                $result = $search->RunQueries();
            } else {
                $search->SetFilter('year', array($year));
                $search->AddQuery($keyword, config('myindex'));	//添加查询（全字段搜索）
                $result = $search->RunQueries();
            }
            $counts = $result[0]["total_found"];
            $data['count'] = $counts;

            if($counts>0){
                $docid = [];
                $unions = '';
                foreach($result[0]['matches'] as $id=>$vo) {
                    $tempID = substr($id,0,4);
                    if(!isset($docid[$tempID])){
                        $docid[$tempID] = '';
                    }
                    $docid[$tempID] = $docid[$tempID] . $id  .',';
                }
                foreach($docid as $id=>$vo) {
                    $unions = $unions . "SELECT `docid`,`mtitle`,`year` FROM s_data_".$id." WHERE docid IN(".trim($vo,',').") UNION ALL ";
                }
                unset($docid);
                $unions = substr($unions,0,-11);
                $data['data'] = Db::query($unions);

                if(empty($year)){
                    if($cpage==1){
                        Cache::rm('ygroup');
                        foreach($result[1]['matches'] as $id=>$vo) {
                            $ygroup[$vo['attrs']['@groupby']] = $vo['attrs']['@count'];
                        }
                        Cache::set('ygroup', $ygroup);
                    }
                }
                $data['year'] = Cache::get('ygroup');
            }

        debug('end');
        $data['code'] = 0;
        $data['msg'] = '';
        $data['times'] = debug('begin','end').'s';
        return $data;
    }

    //获取文章详细信息
    public function getArticle()
    {
        $docid = input('post.docid');
        $data['code'] = 0;
        $data['msg'] = '';
        $data['data'] = '';

        if(!empty($docid)){
            /* 获取信息 */
            $table_name = 's_data_'.substr($docid,0,4);
            $sql = 'select * from '.$table_name.' left join s_source on '.$table_name.'.sid=s_source.s_id where docid='.filter_keyword($docid).' limit 1';
            $res = Db::query($sql);
            $path = base64_encode(Config('downpath').$res[0]['filepath']);
            $data['path'] = $path;
            $data['data'] = $res;
        }
        return $data;
    }

    //刊物搜索
    public function publication()
    {
        $keyword = filter_keyword(input('post.keyword'));
        $type = filter_keyword(input('post.type'));
        $page = filter_keyword(input('post.page'));
        $limit = filter_keyword(input('post.limit'));

        $data['code'] = 0;
        $data['msg'] = '';
        $data['data'] = '';

        if(!empty($type)){
            $startN = $page<=1?0:($page-1)*$limit;
            if(empty($keyword)){
                $countSql = 'select count(*) AS t from s_source where doctype="'.$type.'"';
                $sql = 'select * from s_source where doctype="'.$type.'" limit '.$startN.','.$limit;
            } else {
                $countSql = 'select count(*) AS t from s_source where doctype="'.$type.'" and (sourcename like "%'.$keyword.'%" or sourcename_a like "%'.$keyword.'%")';
                $sql = 'select * from s_source where doctype="'.$type.'" and (sourcename like "%'.$keyword.'%" or sourcename_a like "%'.$keyword.'%") limit '.$startN.','.$limit;
            }
            debug('begin');
            $countRes = Db::query($countSql);
            $data['data'] = Db::query($sql);
            debug('end');
            $data['count'] = $countRes[0]['t'];
            $data['times'] = debug('begin','end').'s';
        }
        return $data;
    }

    //刊内检索
    public function publicationList()
    {
        $keyword = input('post.keyword');
        $sid = intval (input('post.pid'));
        $year = intval (input('post.year'));
        $issue = urldecode(input('post.issue'));
        $cpage = intval (input('post.page'));
        $pagesize = intval (input('post.limit'));

        import('Sphinx.SphinxClient', EXTEND_PATH, '.class.php');
        $search = new \SphinxClient();
        $search->SetServer(config('sphinxhost'),config('sphinxport'));	//服务器地址，端口
        $search->SetMatchMode(SPH_MATCH_EXTENDED2);	// 匹配模式
        $weights = array(
            'mtitle' => 9999,
            'sourcename' => 6666
        );
        $search->SetFieldWeights($weights);	//设置字段权重
        $search->SetSortMode(SPH_SORT_RELEVANCE);	//排序方式 匹配度
        $search->SetLimits(($cpage-1)*$pagesize, $pagesize); //分页设置
        $search->SetFilter('sid', array($sid));
        if(empty($year)){
            $search->AddQuery($keyword, config('myindex'));	//添加查询（全字段搜索）
            if($cpage==1){
                $search->SetLimits(0,50);
                $search->SetGroupBy('year', SPH_GROUPBY_ATTR);	//按年分组
                $search->AddQuery($keyword, config('myindex'));
            }
        } else {
            $search->SetFilter('year', array($year));
            if(empty($issue)){
                $search->AddQuery($keyword, config('myindex'));	//添加查询（全字段搜索）
                if($cpage==1){
                    $search->SetLimits(0,50);
                    $search->SetGroupBy('issues', SPH_GROUPBY_ATTR);	//按期分组
                }
            } else {
                if($issue=='A001'){
                    $search->SetFilter('issues', array(sprintf('%u', crc32(''))));
                }else{
                    $search->SetFilter('issues', array(sprintf('%u', crc32($issue))));
                }
            }
            $search->AddQuery($keyword, config('myindex'));	//添加查询（全字段搜索）
        }
        debug('begin');
        $result = $search->RunQueries();
        $counts = $result[0]["total_found"];
        $data['count'] = $counts;

        if($counts>0){
            $docid = [];
            $unions = '';
            foreach($result[0]['matches'] as $id=>$vo) {
                $tempID = substr($id,0,4);
                if(!isset($docid[$tempID])){
                    $docid[$tempID] = '';
                }
                $docid[$tempID] = $docid[$tempID] . $id  .',';
            }
            foreach($docid as $id=>$vo) {
                $unions = $unions . "SELECT `docid`,`mtitle`,`year` FROM s_data_".$id." WHERE docid IN(".trim($vo,',').") UNION ALL ";
            }
            unset($docid);
            $unions = substr($unions,0,-11);
            $data['data'] = Db::query($unions);

            if(empty($year)){
                if($cpage==1){
                    Cache::rm('ygroup');
                    foreach($result[1]['matches'] as $id=>$vo) {
                        $ygroup[$vo['attrs']['@groupby']] = $vo['attrs']['@count'];
                    }
                    Cache::set('ygroup', $ygroup);
                    $data['year'] = Cache::get('ygroup');
                }
            } else {
                if(empty($issue)){
                    if($cpage==1) {
                        foreach ($result[1]['matches'] as $id => $vo) {
                            if (empty($vo['attrs']['issue'])) {
                                $igroup['A001'] = $vo['attrs']['@count'];
                            } else {
                                $igroup[$vo['attrs']['issue']] = $vo['attrs']['@count'];
                            }
                        }
                        $data['issue'] = $igroup;
                    }
                }
            }
        }
        debug('end');
        $data['code'] = 0;
        $data['msg'] = '';
        $data['times'] = debug('begin','end').'s';
        return $data;
    }

    //文摘数据检索
    public function digest()
    {
        $keyword = input('post.keyword');
        $year = intval (input('post.year'));
        $dataType = urldecode(input('post.dataType'));
        $cpage = intval (input('post.page'));
        $pagesize = intval (input('post.limit'));

        import('Sphinx.SphinxClient', EXTEND_PATH, '.class.php');
        $search = new \SphinxClient();
        $search->SetServer(config('sphinxhost'),config('sphinxport'));	//服务器地址，端口
        $search->SetMatchMode(SPH_MATCH_EXTENDED2);	// 匹配模式
        $weights = array(
            'mtitle' => 9999,
            'sourcename' => 6666
        );
        $search->SetFieldWeights($weights);	//设置字段权重
        $search->SetSortMode(SPH_SORT_RELEVANCE);	//排序方式 匹配度
        $search->SetLimits(($cpage-1)*$pagesize, $pagesize); //分页设置
        $search->SetFilter('cid', array($dataType));
        if(empty($year)){
            $search->AddQuery($keyword, config('myindex'));	//添加查询（全字段搜索）
            if($cpage==1){
                $search->SetLimits(0,50);
                $search->SetGroupBy('year', SPH_GROUPBY_ATTR);	//按年分组
                $search->AddQuery($keyword, config('myindex'));
            }
        } else {
            $search->SetFilter('year', array($year));
            $search->AddQuery($keyword, config('myindex'));	//添加查询（全字段搜索）
        }
        debug('begin');
        $result = $search->RunQueries();
        $counts = $result[0]["total_found"];
        $data['count'] = $counts;

        if($counts>0){
            $docid = [];
            $unions = '';
            foreach($result[0]['matches'] as $id=>$vo) {
                $tempID = substr($id,0,4);
                if(!isset($docid[$tempID])){
                    $docid[$tempID] = '';
                }
                $docid[$tempID] = $docid[$tempID] . $id  .',';
            }
            foreach($docid as $id=>$vo) {
                $unions = $unions . "SELECT `docid`,`mtitle`,`year` FROM s_data_".$id." WHERE docid IN(".trim($vo,',').") UNION ALL ";
            }
            unset($docid);
            $unions = substr($unions,0,-11);
            $data['data'] = Db::query($unions);

            if(empty($year)){
                if($cpage==1){
                    Cache::rm('ygroup');
                    foreach($result[1]['matches'] as $id=>$vo) {
                        $ygroup[$vo['attrs']['@groupby']] = $vo['attrs']['@count'];
                    }
                    Cache::set('ygroup', $ygroup);
                    $data['year'] = Cache::get('ygroup');
                }
            }
        }
        debug('end');
        $data['code'] = 0;
        $data['msg'] = '';
        $data['times'] = debug('begin','end').'s';
        return $data;
    }

    //获取数据库列表
    public function getTableList()
    {
        $res = Db::query('select * from s_class');
        return $res;
    }
}